/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.user.comment.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.dto.OrderRefundDto;
import com.yami.shop.bean.event.BalanceRefundEvent;
import com.yami.shop.bean.model.UserExtension;
import com.yami.shop.bean.pay.RefundInfoDto;
import com.yami.shop.common.util.Arith;
import com.yami.shop.service.OrderRefundService;
import com.yami.shop.service.UserExtensionService;
import com.yami.shop.user.comment.model.UserBalanceLog;
import com.yami.shop.user.comment.service.UserBalanceLogService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 余额支付操作
 *
 * @author lhd
 */
@Component("balanceRefundListener")
@AllArgsConstructor
public class BalanceRefundListener {
    private final UserExtensionService userExtensionService;
    private final UserBalanceLogService userBalanceLogService;
    private final OrderRefundService orderRefundService;

    /**
     * 余额支付操作
     */
    @EventListener(BalanceRefundEvent.class)
    @Transactional(rollbackFor = Exception.class)
    public void levelUpListener(BalanceRefundEvent event) {
        RefundInfoDto refundInfo = event.getRefundInfo();
        Double refundAmount = refundInfo.getRefundAmount();
        OrderRefundDto orderRefund = orderRefundService.getOrderRefundByRefundSn(refundInfo.getRefundSn());
        UserExtension userExtension = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, orderRefund.getUserId()));
        userExtension.setTotalBalance(Arith.add(userExtension.getTotalBalance(), refundAmount));
        userExtension.setUpdateTime(new Date());
        userExtensionService.updateBalanceByVersion(userExtension);
        // 退款金额大于0，则添加余额记录
        if (refundInfo.getRefundAmount() > 0) {
            UserBalanceLog userBalanceLog = new UserBalanceLog();
            userBalanceLog.setUserId(userExtension.getUserId());
            userBalanceLog.setType(4);
            userBalanceLog.setIoType(1);
            userBalanceLog.setChangeBalance(refundInfo.getRefundAmount());
            userBalanceLog.setCreateTime(new Date());
            userBalanceLogService.save(userBalanceLog);
        }
        //退款成功
        OrderRefundDto orderRefundDto = orderRefundService.getOrderRefundByRefundSn(refundInfo.getRefundSn());
        orderRefundService.verifyRefund(orderRefundDto, refundInfo.getRefundSn());
    }
}
